<template>
  <div class="finance-list">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 统计信息 -->
    <div class="stats">
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">待审核订单</div>
          <div class="stat-value">{{ stats.pending_orders }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">待核实记录</div>
          <div class="stat-value">{{ stats.pending_records }}</div>
        </div>
      </el-card>
      <el-card class="stat-card">
        <div class="stat-item">
          <div class="stat-label">本月到账金额</div>
          <div class="stat-value">￥{{ stats.this_month_amount }}</div>
        </div>
      </el-card>
    </div>

    <!-- 操作栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAddRecord">添加到账记录</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" v-loading="loading" stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="order_no" label="订单编号" min-width="150" />
      <el-table-column prop="customer_name" label="客户名称" min-width="150" />
      <el-table-column prop="total_amount" label="订单金额" width="120">
        <template #default="scope">￥{{ scope.row.total_amount }}</template>
      </el-table-column>
      <el-table-column prop="paid_amount" label="已付金额" width="120">
        <template #default="scope">￥{{ scope.row.paid_amount }}</template>
      </el-table-column>
      <el-table-column prop="approval_status" label="审核状态" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.approval_status === 0" type="info">待审核</el-tag>
          <el-tag v-else-if="scope.row.approval_status === 1" type="warning">审核中</el-tag>
          <el-tag v-else type="success">审核通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="handleViewRecords(scope.row)">查看记录</el-button>
          <el-button type="text" @click="handleAddRecord(scope.row)">添加记录</el-button>
          <el-button
            type="text"
            @click="handleVerify(scope.row)"
            v-if="hasFinanceRecord(scope.row)"
          >
            财务审核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.limit"
        :page-sizes="[20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 到账记录对话框 -->
    <el-dialog v-model="recordDialogVisible" title="到账记录" width="800px">
      <div v-if="currentOrder">
        <el-descriptions :column="2" border class="mb-20">
          <el-descriptions-item label="订单编号">{{ currentOrder.order_no }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentOrder.customer_name }}
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">
            ￥{{ currentOrder.total_amount }}
          </el-descriptions-item>
          <el-descriptions-item label="已付金额">
            ￥{{ currentOrder.paid_amount }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 记录表格 -->
        <el-table :data="financeRecords" stripe class="mb-20">
          <el-table-column prop="received_amount" label="到账金额" width="120">
            <template #default="scope">￥{{ scope.row.received_amount }}</template>
          </el-table-column>
          <el-table-column prop="payment_type" label="收款类型" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.payment_type === 1" type="primary">合同应收款</el-tag>
              <el-tag v-else type="warning">后期应收款</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="payment_method" label="收款方式" width="120">
            <template #default="scope">
              {{ getPaymentMethodText(scope.row.payment_method) }}
            </template>
          </el-table-column>
          <el-table-column prop="verification_status" label="核实状态" width="120">
            <template #default="scope">
              <el-tag v-if="scope.row.verification_status === 0" type="info">未核实</el-tag>
              <el-tag v-else type="success">已核实</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                type="text"
                @click="handleVerifyRecord(scope.row)"
                v-if="scope.row.verification_status === 0"
              >
                核实
              </el-button>
              <el-button
                type="text"
                @click="handleDeleteRecord(scope.row)"
                v-if="scope.row.verification_status === 0"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加记录表单 -->
        <el-form :model="recordForm" :rules="recordRules" ref="recordFormRef" label-width="120px">
          <el-divider>添加新记录</el-divider>
          <el-form-item label="收款类型" prop="payment_type">
            <el-radio-group v-model="recordForm.payment_type">
              <el-radio :label="1">合同应收款</el-radio>
              <el-radio :label="2">后期应收款</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="到账金额" prop="received_amount">
            <el-input-number
              v-model="recordForm.received_amount"
              :min="0"
              :precision="2"
              :step="100"
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="到账日期" prop="received_date">
            <el-date-picker
              v-model="recordForm.received_date"
              type="date"
              placeholder="选择日期"
              style="width: 200px"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="收款方式" prop="payment_method">
            <el-select
              v-model="recordForm.payment_method"
              placeholder="请选择"
              style="width: 200px"
            >
              <el-option label="银行转账" :value="1" />
              <el-option label="支付宝" :value="2" />
              <el-option label="微信" :value="3" />
              <el-option label="现金" :value="4" />
              <el-option label="其他" :value="5" />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方名称" prop="payer_name">
            <el-input
              v-model="recordForm.payer_name"
              placeholder="请输入付款方名称"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="recordForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmitRecord">添加</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  // 类型定义
  interface Order {
    id: number
    order_no: string
    customer_name: string
    total_amount: number
    paid_amount: number
    approval_status: number
    create_time: number | string
  }

  interface FinanceRecord {
    id: number
    received_amount: number
    payment_type: number
    payment_method: number
    verification_status: number
    received_date: string
    payer_name: string
    remark: string
  }

  // 搜索表单
  const searchForm = reactive({
    customerName: '',
  })

  // 表格数据
  const tableData = ref<Order[]>([])
  const loading = ref(false)
  const pagination = reactive({
    page: 1,
    limit: 20,
    total: 0,
  })

  // 统计数据
  const stats = reactive({
    pending_orders: 0,
    pending_records: 0,
    this_month_amount: 0,
  })

  // 记录对话框
  const recordDialogVisible = ref(false)
  const currentOrder = ref<Order | null>(null)
  const financeRecords = ref<FinanceRecord[]>([])

  // 记录表单
  const recordFormRef = ref()
  const recordForm = reactive({
    payment_type: 1,
    received_amount: 0,
    received_date: '',
    payment_method: 1,
    payer_name: '',
    remark: '',
  } as {
    payment_type: number
    received_amount: number
    received_date: string
    payment_method: number
    payer_name: string
    remark: string
  })

  // 表单验证规则
  const recordRules = {
    payment_type: [{ required: true, message: '请选择收款类型', trigger: 'change' }],
    received_amount: [{ required: true, message: '请输入到账金额', trigger: 'blur' }],
    received_date: [{ required: true, message: '请选择到账日期', trigger: 'change' }],
    payment_method: [{ required: true, message: '请选择收款方式', trigger: 'change' }],
    payer_name: [{ required: true, message: '请输入付款方名称', trigger: 'blur' }],
  }

  // 初始化
  onMounted(() => {
    fetchData()
    fetchStats()
  })

  // 获取表格数据
  const fetchData = async () => {
    loading.value = true
    try {
      const { financeApi } = await import('@/api/finance')
      const params: any = {
        page: pagination.page,
        limit: pagination.limit,
      }
      if (searchForm.customerName) params.customer_name = searchForm.customerName

      const res = await financeApi.getPendingOrders(params)
      if (res.code === 0) {
        tableData.value = res.data.list || []
        pagination.total = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取数据失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.getFinanceStats()
      if (res.code === 0) {
        Object.assign(stats, res.data)
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchData()
  }

  // 重置
  const handleReset = () => {
    searchForm.customerName = ''
    handleSearch()
  }

  // 查看记录
  const handleViewRecords = async (row: Order) => {
    currentOrder.value = row
    recordDialogVisible.value = true
    await fetchFinanceRecords(row.id)
  }

  // 添加记录
  const handleAddRecord = (row?: Order) => {
    if (row) {
      currentOrder.value = row
    }
    recordDialogVisible.value = true
    resetRecordForm()
  }

  // 获取财务记录
  const fetchFinanceRecords = async (orderId: number) => {
    try {
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.getFinanceRecords(orderId)
      if (res.code === 0) {
        financeRecords.value = res.data.list || []
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取财务记录失败')
    }
  }

  // 检查是否有财务记录
  const hasFinanceRecord = (row: Order) => {
    // 根据订单的已付金额判断
    return row.paid_amount > 0
  }

  // 核实记录
  const handleVerifyRecord = async (record: FinanceRecord) => {
    try {
      await ElMessageBox.confirm('确定要核实此记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.verifyFinanceRecord(record.id)
      if (res.code === 0) {
        ElMessage.success('核实成功')
        if (currentOrder.value) {
          await fetchFinanceRecords(currentOrder.value.id)
        }
      } else {
        ElMessage.error(res.msg || '核实失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 删除记录
  const handleDeleteRecord = async (record: FinanceRecord) => {
    try {
      await ElMessageBox.confirm('确定要删除此记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.deleteFinanceRecord(record.id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        if (currentOrder.value) {
          await fetchFinanceRecords(currentOrder.value.id)
        }
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 财务审核
  const handleVerify = async (row: Order) => {
    try {
      await ElMessageBox.confirm('确定要通过财务审核吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.financeApproval(row.id)
      if (res.code === 0) {
        ElMessage.success('审核通过')
        fetchData()
        fetchStats()
      } else {
        ElMessage.error(res.msg || '审核失败')
      }
    } catch (error) {
      console.log('用户取消')
    }
  }

  // 提交记录
  const handleSubmitRecord = async () => {
    await recordFormRef.value.validate()
    if (!currentOrder.value) {
      ElMessage.error('订单信息异常')
      return
    }
    try {
      const { financeApi } = await import('@/api/finance')
      const res = await financeApi.addFinanceRecord({
        order_id: currentOrder.value.id,
        payment_type: recordForm.payment_type,
        received_amount: recordForm.received_amount,
        received_date: recordForm.received_date,
        payment_method: recordForm.payment_method,
        payer_name: recordForm.payer_name,
        remark: recordForm.remark,
      })
      if (res.code === 0) {
        ElMessage.success('添加成功')
        resetRecordForm()
        if (currentOrder.value) {
          await fetchFinanceRecords(currentOrder.value.id)
        }
        fetchData()
        fetchStats()
      } else {
        ElMessage.error(res.msg || '添加失败')
      }
    } catch (error) {
      ElMessage.error('添加失败')
    }
  }

  // 重置记录表单
  const resetRecordForm = () => {
    recordForm.payment_type = 1
    recordForm.received_amount = 0
    recordForm.received_date = ''
    recordForm.payment_method = 1
    recordForm.payer_name = ''
    recordForm.remark = ''
  }

  // 分页
  const handleSizeChange = (val: number) => {
    pagination.limit = val
    fetchData()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    fetchData()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number | string) => {
    if (!timestamp) return ''
    const date = new Date(
      typeof timestamp === 'string' ? parseInt(timestamp) * 1000 : timestamp * 1000
    )
    return date.toLocaleString()
  }

  // 获取支付方式文本
  const getPaymentMethodText = (method: number) => {
    const map: Record<number, string> = {
      1: '银行转账',
      2: '支付宝',
      3: '微信',
      4: '现金',
      5: '其他',
    }
    return map[method] || '未知'
  }
</script>

<style lang="scss" scoped>
  .finance-list {
    padding: 20px;

    .search-bar {
      background: #f5f5f5;
      padding: 20px;
      border-radius: 4px;
      margin-bottom: 20px;
    }

    .stats {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;

      .stat-card {
        flex: 1;

        .stat-item {
          text-align: center;

          .stat-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #409eff;
          }
        }
      }
    }

    .toolbar {
      margin-bottom: 20px;
    }

    .pagination {
      margin-top: 20px;
      text-align: right;
    }

    .mb-20 {
      margin-bottom: 20px;
    }
  }
</style>
